﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Adams.Admin.DataAccess.JummahPrayers
{
    public static class CreatePrayer
    {
        public static Adams.Admin.DataTransfer.JummahPrayers.CreatePrayer.PageLoad PageLoad(int id)
        {
            var data = new Adams.Admin.DataTransfer.JummahPrayers.CreatePrayer.PageLoad();
            data.Prayer = new Shared.Entities.JummahPrayers.Prayer();
            data.Prayer.Location = new Shared.Entities.JummahPrayers.Location();
            data.Locations = new Shared.Entities.JummahPrayers.LocationCollection();

            using (SqlDataReader dr = DB.RunDataReader(@"
IF (@PrayerID > 0)
BEGIN
    SELECT * FROM JummahPrayers.Prayers WHERE PrayerID = @PrayerID
END

SELECT * FROM JummahPrayers.Locations ORDER BY Name
", CommandType.Text,
            DB.CreateParameter("@PrayerID", id, SqlDbType.Int)))
            {
                if (id > 0)
                {
                    dr.Read();
                    data.Prayer.ID = dr["PrayerID"].DbInt();
                    data.Prayer.Name = dr["Name"].DbString();
                    data.Prayer.Time = dr["Time"].DbString();
                    data.Prayer.DisplayOrder = dr["DisplayOrder"].DbInt();
                    data.Prayer.Location.ID = dr["LocationID"].DbInt();
                    dr.NextResult();
                }
    
                while (dr.Read())
                {
                    var location = new Shared.Entities.JummahPrayers.Location();
                    location.ID = dr["LocationID"].DbInt();
                    location.Name = dr["Name"].DbString();
                    data.Locations.Add(location);
                }
            }

            return data;
        }

        public static void Save(DataTransfer.JummahPrayers.CreatePrayer.FormInput input)
        {
            DB.Run(@"
IF(@PrayerID > 0)
BEGIN
    UPDATE JummahPrayers.Prayers SET
        Name = @Name,
        Time = @Time,
        DisplayOrder = @DisplayOrder,
        LocationID = @LocationID
    WHERE PrayerID = @PrayerID
END
ELSE
BEGIN
    INSERT INTO JummahPrayers.Prayers (
        Name,
        Time,
        DisplayOrder,
        LocationID)
    VALUES (
        @Name,
        @Time,
        @DisplayOrder,
        @LocationID)
END
    ", CommandType.Text,
                    DB.CreateParameter("@PrayerID", input.ID.ToInt(), SqlDbType.Int),
                    DB.CreateParameter("@LocationID", input.Location.ToNString(), SqlDbType.Int),
                    DB.CreateParameter("@Name", input.Name.ToNString(), SqlDbType.VarChar, 50),
                    DB.CreateParameter("@Time", input.Time.ToNString(), SqlDbType.VarChar, 50),
                    DB.CreateParameter("@DisplayOrder", input.DisplayOrder.ToNString(), SqlDbType.Int));
        }
    }
}
